package com.project.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 验证码控制器
 */
@Slf4j
@RestController
@RequestMapping("captcha")
public class CaptchaController {

    private static final int WIDTH = 100;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;

    /**
     * 获取验证码图片
     */
    @GetMapping("/get")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response, 
                          @RequestParam(required = false) String t) throws IOException {
        // 生成随机验证码
        String code = generateCode();
        
        // 将验证码存入session，使用时间戳作为key
        HttpSession session = request.getSession();
        String sessionKey = "captcha_" + (t != null ? t : session.getId());
        session.setAttribute(sessionKey, code);
        session.setAttribute(sessionKey + "_time", System.currentTimeMillis());
        
        // 设置响应头
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        
        // 生成图片
        BufferedImage image = generateImage(code);
        
        // 输出图片
        ImageIO.write(image, "PNG", response.getOutputStream());
    }

    /**
     * 验证验证码
     */
    @PostMapping("/verify")
    public Map<String, Object> verifyCaptcha(HttpServletRequest request, 
                                              @RequestParam String code,
                                              @RequestParam(required = false) String captcha_id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            HttpSession session = request.getSession();
            String sessionKey = "captcha_" + (captcha_id != null ? captcha_id : session.getId());
            String sessionCode = (String) session.getAttribute(sessionKey);
            Long sessionTime = (Long) session.getAttribute(sessionKey + "_time");
            
            // 检查验证码是否存在
            if (sessionCode == null) {
                result.put("result", false);
                result.put("message", "验证码已过期，请刷新验证码");
                return result;
            }
            
            // 检查验证码是否过期（5分钟）
            if (sessionTime != null && System.currentTimeMillis() - sessionTime > 5 * 60 * 1000) {
                session.removeAttribute(sessionKey);
                session.removeAttribute(sessionKey + "_time");
                result.put("result", false);
                result.put("message", "验证码已过期，请刷新验证码");
                return result;
            }
            
            // 验证码不区分大小写
            if (sessionCode.equalsIgnoreCase(code)) {
                // 验证成功后删除验证码
                session.removeAttribute(sessionKey);
                session.removeAttribute(sessionKey + "_time");
                result.put("result", true);
                result.put("message", "验证成功");
            } else {
                result.put("result", false);
                result.put("message", "验证码错误");
            }
        } catch (Exception e) {
            log.error("验证验证码失败", e);
            result.put("result", false);
            result.put("message", "验证失败");
        }
        
        return result;
    }

    /**
     * 生成随机验证码
     */
    private String generateCode() {
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(chars.charAt(random.nextInt(chars.length())));
        }
        return code.toString();
    }

    /**
     * 生成验证码图片
     */
    private BufferedImage generateImage(String code) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        
        // 设置抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        
        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        
        // 绘制干扰线
        Random random = new Random();
        g.setColor(Color.LIGHT_GRAY);
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
        
        // 绘制验证码
        g.setFont(new Font("Arial", Font.BOLD, 28));
        for (int i = 0; i < code.length(); i++) {
            g.setColor(new Color(random.nextInt(100), random.nextInt(100), random.nextInt(100)));
            int x = 20 + i * 20;
            int y = 25 + random.nextInt(10);
            g.drawString(String.valueOf(code.charAt(i)), x, y);
        }
        
        // 绘制干扰点
        for (int i = 0; i < 50; i++) {
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            g.setColor(new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200)));
            g.fillOval(x, y, 2, 2);
        }
        
        g.dispose();
        return image;
    }
}



